<template>
	<view class="container">
		<!-- 返回按钮 -->
		<view class="navback-container">
			<navigator open-type="navigateBack">
				<u-icon name="arrow-left" color="#fff" size="24"></u-icon>
			</navigator>
		</view>
		<!-- 轮播 -->
		<view class="swiper-container">
			<u-swiper :list="product.imgList" :interval="5000" height="360" radius="0" circular indicator indicatorMode="dot" indicatorStyle="font-size:36px;"></u-swiper>
		</view>

		<!-- 商品信息 -->
		<view class="indroduce-container">
			<view class="title">{{product.title}}</view>
			<view class="price-wraper">
				<view class="sign">¥</view>
				<view class="price" v-if="product.activity">
					{{choosedProduct && choosedProduct.groupSku && choosedProduct.groupSku.skuGroupShopPrice/100 }}
				</view>
				<view class="price" v-else>{{isVip? choosedProduct.vipPrice/100:choosedProduct.price/100}}</view>
				<view class="originalPrice">¥{{ choosedProduct.originalPrice/100}}</view>
				<view class="discount" v-if="product.activity">团购价</view>
				<view v-else>
					<text v-if="isVip" class="discount">VIP价</text>
					<text v-else class="discount">
						{{calcDiscount(isVip? choosedProduct.vipPrice:choosedProduct.price,choosedProduct.originalPrice)}}折
					</text>
				</view>
			</view>
			<view class="count-wraper">
				<u-row>
					<u-col :span="6">
						<text>销量：{{product.sales}}</text>
					</u-col>
					<u-col :span="6">
						<text>库存：{{totalStock}}</text>
					</u-col>
				</u-row>
			</view>
			<view class="option-wraper">
				<uni-list class="list-wraper">
					<uni-list-item class="group-item" v-if="product.activity">
						<template v-slot:header>
							<view class="title-wraper">
								<view style="display: inline-block;width: 150rpx;">
									<view class="group-icon">
										<u-icon name="star-fill" size="12" color="#fff" bgColor="#fa436a"></u-icon>
										团
									</view>
								</view>
								<text style="font-size: 28rpx;" v-if="product.activity">{{product.activity.minNum}}人成团，已有{{product.activity.buyerNum}}人参团</text>
							</view>
						</template>
						<template v-slot:footer>
							<view class="group-right">
								<u-icon name="question-circle"></u-icon>
								<text style="margin-left: 8px;">告诉TA</text>
								<u-icon name="arrow-right" color="#fa436a"></u-icon>
							</view>
						</template>
					</uni-list-item>
					<uni-list-item link @click="showSpu=true">
						<template v-slot:header>
							<view class="title-wraper">
								<text style="display: inline-block;width: 90px;">购买类型</text>
								<text>{{choosedProduct.title}}</text>
							</view>
						</template>
					</uni-list-item>
					<uni-list-item link @click="showCoupon=true" v-if="coupList.length>0">
						<template v-slot:header>
							<view class="title-wraper">
								<text style="display: inline-block;width: 90px;">优惠券</text>
								<text style="color: #fa436a;">领取优惠券</text>
							</view>
						</template>
					</uni-list-item>
					<uni-list-item>
						<template v-slot:header>
							<view class="title-wraper">
								<text style="display: inline-block;width: 90px;">配送费用</text>
								<text v-if="product.freightTemplate&&product.freightTemplate.defaultFreePrice/100===0">包邮</text>
								<text v-else>单笔购买满¥{{product.freightTemplate&&product.freightTemplate.defaultFreePrice / 100}}元免邮费</text>
							</view>
						</template>
					</uni-list-item>
					<uni-list-item v-for="item in product.attributeList">
						<template v-slot:header>
							<view class="title-wraper">
								<text style="display: inline-block;width: 90px;">{{item.attribute}}</text>
								<text>{{item.value}}</text>
							</view>
						</template>
					</uni-list-item>
				</uni-list>
			</view>
		</view>
		<u-gap height="10px"></u-gap>
		<!-- 商品详情 -->
		<view class="detail-container">
			<view class="title">
				<u-divider text="图文详情" textColor="#333" lineColor="#666"></u-divider>
			</view>
			<view class="content">
				<u-parse :content="product.detail"></u-parse>
			</view>
		</view>
		<!-- 底部空行占位 -->
		<view style="height: 85px;"></view>
		<!-- 底部操作按钮 -->
		<view class="bottom-container">
			<view class="bottom-wraper">
				<view class="button-box">
					<u-grid :col="3" :border="false">
						<u-grid-item :span="4">
							<navigator url="/pages/index/index" open-type="switchTab">
								<u-icon name="home" size="24" color="#8c8c8c"></u-icon>
								<view>首页</view>
							</navigator>
						</u-grid-item>
						<u-grid-item :span="4">
							<navigator url="/pages/cart/cart" open-type="switchTab">
								<u-icon name="shopping-cart-fill" color="#8c8c8c" size="25"></u-icon>
								<view>购物车</view>
							</navigator>
						</u-grid-item>
						<u-grid-item :span="4" @click="favoriteProduct()">
							<u-icon name="heart-fill" size="24" :color="product.favorite?'#fa436a':'#8c8c8c'"></u-icon>
							<view>收藏</view>
						</u-grid-item>
					</u-grid>
					<view class="buy-box-wraper">
						<u-row>
							<u-col :span="6">
								<button plain size="mini" hover-class="tab-button" class="button" @click="createOrder">{{product.activity?"立即参团":"立即购买"}}</button>
							</u-col>
							<u-col :span="6">
								<button plain size="mini" hover-class="tab-button" class="button" @click="addCartItem">加入购物车</button>
							</u-col>
						</u-row>
					</view>
				</view>
			</view>
		</view>
		<!-- 弹层 -->
		<view class="pop-container">
			<!-- 优惠券弹层 -->
			<view class="coupon-wraper">
				<u-popup :show="showCoupon" @close="showCoupon=false" bgColor="#f5f5f5">
					<view class="coupon-content">
						<!-- template的妙用 -->
						<template v-for="(item,index) in coupList">
							<view class="coupon-item" :class="{'geted':item.limit==item.nowCount}" @click="obtainCoupon(item.id)">
								<view class="header-wraper">
									<view class="desc-wraper">
										<view><text>{{item.title}}</text></view>
										<view class="desc">
											<text>
												<template v-if="item.days">
													在领取后{{item.days}}天内有效
												</template>
												<template v-else>
													在{{$u.timeFormat(item.gmtUpdate, 'yyyy年mm月dd日')}}前有效
												</template>
												。可领{{item.limit}}张，已领{{item.nowCount}}张
											</text>
										</view>
									</view>
									<view class="price-wraper">
										<view><text class="sign">￥</text><text class="price">{{item.discount/100}}</text></view>
										<view class="condition">满{{item.min/100}}可用</view>
									</view>
								</view>
								<view class="divider-line"></view>
								<view class="cate">
									<text>{{item.categoryTitle?`限${item.categoryTitle}可用`:"全品类可用"}}</text>
								</view>
							</view>
							<u-gap height="10" v-if="index!=coupList.length-1"></u-gap>
						</template>
					</view>
				</u-popup>
			</view>
			<!-- 商品规格属性弹层 -->
			<view class="spu-wraper">
				<u-popup :show="showSpu" @close="showSpu=false;finishRun = null;" @open="openedSpuWindow">
					<view class="spu-content">
						<!-- 头部 -->
						<view class="spu-header">
							<view class="header-wraper">
								<u--image radius="3px" width="85px" height="85px" :src="choosedProduct.img"> </u--image>
							</view>
							<view class="desc-wraper">
								<view class="price" v-if="product.activity">
									<text>¥{{choosedProduct && choosedProduct.groupSku&& choosedProduct.groupSku.skuGroupShopPrice/100}}</text>
									<text class="tag" style="margin-left: 5px;">团购价</text>
								</view>
								<view class="price" v-else>
									<text>¥{{isVip? choosedProduct.vipPrice/100:choosedProduct.price/100}}</text>
									<text v-if="isVip" class="tag" style="margin-left: 5px;">会员价</text>
								</view>
								<view><text>库存：{{choosedProduct.stock}}件</text></view>
								<view><text>已选：{{choosedProduct.title}}</text></view>
							</view>
						</view>
						<!-- spu详情 -->
						<view class="det-wraper">
							<scroll-view scroll-y="true" class="scroll-container">
								<view class="spu" v-for="key in Object.keys(skuMap)">
									<view class="title-wraper">
										<text class="title">{{key}}</text>
									</view>
									<view class="spu-item-wraper">
										<view class="item" v-for="item in skuMap[key]">
											<u-button plain shape="circle" size="mini" :type="item==choosedSku[key]?'success':'default'" @click="handleSkuClick(key,item)">{{item}}
											</u-button>
										</view>
									</view>
								</view>
								<view class="spu">
									<view class="title-wraper">
										<text class="title">数量</text>
									</view>
									<view class="spu-item-wraper">
										<view class="item">
											<u-number-box v-model="count" min="1" :max="choosedProduct.stock">
											</u-number-box>
										</view>
									</view>
								</view>
								<view>
									<u-button @click="handleChoseDone" size="small" shape="circle" customStyle="padding:6px 0;font-size: 14px; background-color: #fa436a;"
										type="error">
										完成</u-button>
								</view>
							</scroll-view>
						</view>
					</view>
				</u-popup>
			</view>
		</view>
	</view>
</template>
<script>
	import { post, get } from "@/http/index.js"
	//注意：导入进来的函数或对象只能在<script>直接使用，不能再<template>里使用，如果需要使用，要在data函数上注册进来
	import { isVip, calcDiscount } from "@/util/index.js"
	//全局变量，用于页面之间传值
	import { $skuList } from "@/globaldata/index.js"
	export default {
		data() {
			return {
				calcDiscount, //导入的函数直接在模板使用时，需要通过data暴露，否则报错
				isVip: false, //是否为VIP用户
				id: 0, //商品主键编号
				product: {}, //商品
				showCoupon: false, //显示优惠券
				showSpu: false, //显示商品规格
				count: 1, //购买数量
				choosedSku: {}, //选中的规格属性
				coupList: [], //优惠券列表  
				finishRun: null, //点击完成后要执行的函数
			};
		},
		computed: {
			//库存总量
			totalStock() {
				return (this.product.skuList || []).reduce((total, current) => {
					return total + current.stock;
				}, 0)
			},
			//sku 键值    
			skuMap() {
				let skuList = this.product.skuList || [];
				let len = skuList.length;
				if (0 == len) {
					return {};
				}
				let sku = skuList[0];
				let map = {};
				sku.specification.split(",").forEach(item => {
					let array = item.split("_");
					map[array[0]] = [array[1]]; // 动态key名
				});
				//去重累加规格属性值
				for (let i = 1; i < skuList.length; i++) {
					let sku = skuList[i];
					let titleArray = sku.title.split(",");
					let keys = Object.keys(map);
					keys.forEach((key, index) => {
						if (!map[key].includes(titleArray[index])) { //去重处理
							map[key].push(titleArray[index]); //累加规格属性值
						}
					});
				}
				return map;
			},
			//是否有选规格
			hasChooseSku() {
				let that = this;
				let choosedSku = that.choosedSku || {};
				let skuKeys = Object.keys(choosedSku);
				return skuKeys.length > 0;
			},
			//被选中的商品
			choosedProduct() {
				console.log("[计算属性]choosedProduct");
				let that = this;
				let skuList = that.product.skuList || [];
				let choosedSku = that.choosedSku;
				let skuKeys = Object.keys(choosedSku);
				//没用选规格
				if (0 == skuKeys.length) {
					//商品默认价格
					const { price, vipPrice, originalPrice } = that.product;
					let groupSku = that.product.activity?.groupShopSkuDTOList[0];
					return { price, vipPrice, originalPrice, groupSku };
				}
				let specification = skuKeys.map(key => key + "_" + choosedSku[key]).join();
				let product = skuList.find(item => item.specification === specification);
				// debugger
				//团购处理
				if (that.product.activity && product) {
					let skuId = product.id;
					let groupSkuList = that.product.activity.groupShopSkuDTOList || [];
					let groupSku = groupSkuList.find(item => item.skuId == skuId) || {};
					// that.$set(product, "groupSku", groupSku); //为product对象附加团购信息
					product.groupSku = groupSku; //为product对象附加团购信息
				}
				return product || {};
			},
		},
		onShow() {
			this.isVip = isVip(); //isVip()是导入进来的函数，在js中可以直接使用
		},
		onLoad(options) {
			this.id = options.id || 0;
			this.loadProduct();
			this.getCouponList();
		},
		methods: {
			loadProduct() {
				let that = this;
				if (!that.id) {
					return; //无效的ID，没有请求接口的必要
				}
				get("product", "getProduct", {
					spuId: that.id
				}).then(res => {
					that.product = res.data;
				}).catch(err => {
					console.error(err);
				})
			},
			//规格属性弹层
			openedSpuWindow() {
				let that = this;
				let keys = Object.keys(that.choosedSku);
				if (0 === keys.length) {
					//默认挑选第一个
					let skuKeys = Object.keys(that.skuMap);
					skuKeys.forEach(key => {
						//【错误】在Vue2中，这不是响应式更新，依赖choosedSku的计算属性以及模板中的:type="item==choosedSku[key]?'success':'default'"都将不会响应式更新哦
						//that.choosedSku[key] = that.skuMap[key][0];//【错误代码】
						that.$set(that.choosedSku, key, that.skuMap[key][0]) //【正确代码】参考地址 https://v2.cn.vuejs.org/v2/api/#Vue-set
					});
					// that.$forceUpdate(); //强制更新，否则第一次弹层就没有选中颜色
				}
			},
			//规格选择
			handleSkuClick(key, value) {
				//对象的响应式更新
				// this.$set(this.choosedSku, key, value);
				//如果这个key已经存在，那么下面的做法也是响应式，如果这个key不存在，下面的做法不是响应式的
				this.choosedSku[key] = value;
			},
			//获取优惠券
			getCouponList() {
				let that = this;
				get("coupon", "getObtainableCoupon").then(res => {
					console.log(res.data);
					that.coupList = res.data;
				}).catch(err => {
					console.log(err)
				})
			},
			//领取优惠券
			obtainCoupon(id) {
				let that = this;
				post("coupon", "obtainCoupon", {
					couponId: id
				}).then(res => {
					uni.showToast({
						title: '领取成功'
					});
					that.getCouponList();
				}).catch(err => {

				})
			},
			//收藏商品
			favoriteProduct() {
				let that = this;
				post("favorite", that.product.favorite ? "delete" : "create", {
					spuId: that.product.id
				}).then(res => {
					uni.showToast({
						title: that.product.favorite ? "取消收藏" : "收藏成功"
					});
					that.product.favorite = !that.product.favorite;
				}).catch(err => {
					console.error(err);
				})
			},
			//下订单
			createOrder() {
				let that = this;
				if (this.hasChooseSku) {
					let pro = that.choosedProduct;
					let skuItem = {
						skuId: pro.id, //规格编号
						num: that.count, //购买数量
						title: that.product.title, //商品标题
						freightTemplateId: that.product.freightTemplateId, //运费模板编号
						originalPrice: pro.originalPrice, //原价
						price: pro.groupSku && pro.groupSku.skuGroupShopPrice || (that.isVip ? pro.vipPrice : pro.price), //当前价
						vipPrice: pro.vipPrice, //vip价
						skuTitle: pro.title, //规格标题
						spuImg: that.product.img, //商品图片
						skuImg: pro.img, //规格图片
						stock: pro.stock, //所选规格的库存
						spuId: that.product.id, //商品编号
						categoryId: that.product.categoryId, //类型编号
						categoryIdList: that.product.categoryIds, //类型层级
						weight: pro.weight //商品的重量
					}
					if (that.product.activity) {
						skuItem['groupShopId'] = pro.groupSku.id;
					}
					//【注意】$skuList为只读属性，不能直接赋值，import 表达式引入进来的所有模块都是只读形式，es6新特性
					// $skuList=[skuItem];//错误
					$skuList.length = 0; //清空数组
					$skuList.push(skuItem); //追加数组
					uni.navigateTo({
						url: `/pages/order/create?takeway=buy`
					});
				} else {
					that.showSpu = true;
					that.finishRun = that.createOrder;
				}
			},
			/**
			 * 加入购物车
			 */
			addCartItem() {
				let that = this;
				let choosedProduct = that.choosedProduct;
				if (choosedProduct.id) {
					let data = {
						num: that.count,
						skuId: choosedProduct.id
					}
					post("cart", "addCartItem", data).then(res => {
						if (choosedProduct.groupSku) {
							uni.showToast({ title: '从购物车结算不会参加团购' });
						} else {
							uni.showToast({ title: '添加购物车成功' });
						}

					}).catch(err => {
						console.error(err);
					})
				} else {
					that.showSpu = true;
					that.finishRun = that.addCartItem;
				}
			},
			/**
			 * 点击完成
			 */
			handleChoseDone() {
				let that = this;
				that.showSpu = false
				if (that.finishRun) {
					that.finishRun();
					that.finishRun = null;
				}
			}

		},
	}
</script>
<style>
	.tab-button {
		color: #666 !important;
		background-color: #e1e1e12e !important;
	}
</style>
<style lang='scss' scoped>
	/* 圆的公共部分 */
	.circle {
		content: '';
		display: block;
		position: absolute;
		top: -10px;
		background-color: #f5f5f5;
		height: 20px;
		width: 20px;
		border-radius: 50%;
	}


	.container {

		.tag {
			background-color: $red;
			color: $white;
			display: inline-block;
			font-size: 12px;
			padding: 0 6px;
			border-radius: 5px;

		}

		/* 返回按钮 */
		.navback-container {
			position: fixed;
			display: flex;
			align-items: center;
			justify-content: center;
			left: 8px;
			top: 8px;
			width: 35px;
			height: 35px;
			background-color: #353535ba;
			z-index: 999999;
			border-radius: 50%;
		}

		/* 轮播 */
		.swiper-container /deep/ {
			.u-swiper {
				.u-swiper-indicator__wrapper__dot {
					width: 9px;
					height: 9px;
				}
			}
		}

		/* 商品信息 */
		.indroduce-container /deep/ {
			background-color: $white;
			padding: 15px 15px 0;

			.price-wraper {
				display: flex;
				padding: 8px 0;
				align-items: center;

				.sign {
					font-size: 14px;
					position: relative;
					color: #fa436a;
				}

				.price {
					color: $red;
					font-size: 17px;
				}

				.originalPrice {
					font-size: 13px;
					margin: 0 8px 0;
					text-decoration: line-through;
					color: #777;
				}

				.discount {
					background-color: $red;
					color: $white;
					font-size: 12px;
					line-height: 16px;
					height: 16px;
					padding: 0 6px;
					position: relative;
				}
			}

			.count-wraper {
				font-size: 12px;
				color: #777;
			}

			.option-wraper {
				margin: 15px -15px 0;

				.list-wraper {
					.uni-list--border-top {
						display: none;
					}

					/* 团购项目 */
					.group-item {
						background-color: #f5f5f5; //用于H5

						.uni-list-item {
							background-color: #f5f5f5; //用于微信小程序

							.uni-list--border {
								display: none;
							}
						}
					}

					.title-wraper {
						font-size: 13px;

						.group-icon {
							background-color: #fa436a0a;
							border: 1px solid #fa436a;
							display: flex;
							width: 36px;
							color: #fa436a;
							align-items: center;
							box-sizing: border-box;
							height: 17px;

							.u-icon {
								background-color: #fa436a;
								padding: 0 2px;
								border-top-right-radius: 5px;
								border-bottom-right-radius: 5px;
								margin-right: 3px;
								height: 15px;
							}
						}
					}

					.group-right {
						display: flex;
						font-size: 12px;
						color: $red;
						align-items: center;
					}

				}

			}
		}

		/* 商品详情 */
		.detail-container {
			background-color: $white;

			.title {
				padding: 15px 0;

				.u-divider {
					margin: auto;
					width: 150px;
				}
			}
		}

		/* 底部操作按钮 */
		.bottom-container {
			.bottom-wraper /deep/ {
				font-size: 13px;
				position: fixed;
				left: 50%;
				transform: translateX(-50%);
				border-radius: 5px;
				bottom: 15px;
				width: 90vw;
				background-color: $white;
				box-shadow: #888 0 0 11px 2px;

				.button-box {
					display: flex;

					.u-grid {
						width: 320rpx;
						color: #666;

						.u-grid-item {
							padding: 5px 0 7px;
						}
					}
				}

				.buy-box-wraper {
					display: flex;
					align-items: center;

					.u-row {
						position: relative;
						width: 340rpx;
						border-radius: 100px;
						background: linear-gradient(to right, #ffac30, #fa436a, #F56C6C);
						box-shadow: #ff8e8ebf 0px 2px 6px 0px;

						.button {
							color: $white;
							padding: 5px 0;
							width: 100%;
							border: none;
						}

						&::after {
							content: '';
							display: block;
							position: absolute;
							left: 50%;
							transform: translateX(-50%);
							height: 13px;
							width: 1px;
							background-color: #efefef;
						}
					}
				}
			}
		}

		/* 弹层 */
		.pop-container {

			/* 优惠券 */
			.coupon-wraper /deep/ {
				.coupon-content {
					padding: 10px;

					.coupon-item {
						background-color: $white;
						padding: 15px;

						&.geted {
							background: url(/static/geted.png) right 12px bottom 0 /45px 45px no-repeat $white;
						}

						.header-wraper {
							display: flex;
							justify-content: space-between;

							.desc-wraper {
								.desc {
									font-size: 12px;
									color: #777;
									line-height: 25px;
								}
							}

							.price-wraper {
								text-align: center;
								color: $red;

								.sign {
									font-size: 17px;
								}

								.price {
									font-size: 21px;
								}

								.condition {
									font-size: 13px;
									color: #333;
								}
							}
						}

						.divider-line {
							height: 1px;
							margin: 6px -15px;
							border-bottom: 1px dashed #efefef;
							position: relative;

							&::before {
								@extend .circle;
								/*继承公共部分样式*/
								left: -9px;
							}

							&::after {
								@extend .circle;
								/*继承公共部分样式*/
								right: -9px;
							}
						}

						.cate {
							font-size: 12px;
							color: #777;
						}
					}
				}
			}

			/* 商品规格属性弹层 */
			.spu-wraper /deep/ {
				.u-popup__content {
					border-top-left-radius: 7px;
					border-top-right-radius: 7px;
					color: #333;

					.spu-content {
						padding: 0 15px 15px;

						.spu-header {
							display: flex;

							.header-wraper {
								position: relative;
								margin-right: 12px;

								.u-image {
									position: relative;
									top: -14px;
								}
							}

							.desc-wraper {
								font-size: 13px;
								line-height: 1.8;

								.price {
									color: $red;
									font-size: 16px;
								}
							}
						}

						.det-wraper {
							.scroll-container {
								height: 800rpx;

								.spu-item-wraper {
									display: flex;
									flex-wrap: wrap;
									padding: 15px 0;

									.item {
										margin-right: 12px;
										margin-bottom: 12px;

										.u-button {
											height: 30px;
											min-width: 30px;
											font-size: 14px;
											border: none;
											background-color: #e5e5e5c1;
											color: #333;

											&.u-button--success {
												background-color: #f56c6c29;
												color: $red;
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}
</style>
